#include "qqmessagewidget.h"

#include <QPainter>
#include <QFontMetrics>
#include <QDateTime>
QQMessageWidget::QQMessageWidget(const QQMessage& msg, bool isSelf, QWidget* parent)
    : QWidget(parent), m_msg(msg), m_isSelf(isSelf)
{
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
}
QSize QQMessageWidget::sizeHint() const {
    const int maxWidth = parentWidget() ? parentWidget()->width() * 0.7 : 400;
    QFontMetrics fm(font());

    // 计算内容高度
    int contentWidth = maxWidth - 2*H_MARGIN - AVATAR_SIZE - 20;
    int lineHeight = fm.lineSpacing();
    int totalHeight = 0;

    foreach (const QString& line, m_msg.content) {
        totalHeight += (fm.horizontalAdvance(line) / contentWidth + 1) * lineHeight;
    }

    // 气泡总高度 = 内容高度 + 时间戳高度 + 边距
    int bubbleHeight = totalHeight + fm.height()*2 + 4*V_MARGIN;
    return QSize(maxWidth, qMax(bubbleHeight, AVATAR_SIZE + 2*V_MARGIN));
}
void QQMessageWidget::paintEvent(QPaintEvent*) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 布局计算
    m_avatarRect = QRect(m_isSelf ? width()-AVATAR_SIZE-H_MARGIN : H_MARGIN,
                         V_MARGIN, AVATAR_SIZE, AVATAR_SIZE);

    int bubbleWidth = width() - 2*H_MARGIN - AVATAR_SIZE - 10;
    m_bubbleRect = QRect(m_isSelf ? H_MARGIN : (AVATAR_SIZE + 2*H_MARGIN),
                         V_MARGIN,
                         bubbleWidth,
                         height() - 2*V_MARGIN);

    m_contentRect = m_bubbleRect.adjusted(10, 10, -10, -30);
    m_timeRect = QRect(m_bubbleRect.left(), m_bubbleRect.bottom()-25,
                       m_bubbleRect.width(), 20);
    paintAvatar(painter);
    paintBubble(painter);
    paintContent(painter);
    paintTimestamp(painter);
}
void QQMessageWidget::paintBubble(QPainter& painter) {
    painter.save();
    QPainterPath path;
    path.addRoundedRect(m_bubbleRect, BUBBLE_RADIUS, BUBBLE_RADIUS);

    // 绘制气泡箭头
    if (m_isSelf) {
        path.moveTo(m_bubbleRect.right(), m_bubbleRect.top() + 15);
        path.lineTo(m_bubbleRect.right() + 6, m_bubbleRect.top() + 20);
        path.lineTo(m_bubbleRect.right(), m_bubbleRect.top() + 25);
    } else {
        path.moveTo(m_bubbleRect.left(), m_bubbleRect.top() + 15);
        path.lineTo(m_bubbleRect.left() - 6, m_bubbleRect.top() + 20);
        path.lineTo(m_bubbleRect.left(), m_bubbleRect.top() + 25);
    }

    painter.setPen(Qt::NoPen);
    painter.setBrush(m_isSelf ? QColor("#95EC69") : QColor("#6a99c5"));
    painter.drawPath(path);
    painter.restore();
}
void QQMessageWidget::paintContent(QPainter& painter) {
    painter.save();
    painter.setPen(Qt::black);
    painter.setFont(font());

    QFontMetrics fm(font());
    int y = m_contentRect.top() + 5;
    int lineHeight = fm.lineSpacing();
    int availableWidth = m_contentRect.width() - 10;  // 保留右侧10px边距

    foreach (const QString& line, m_msg.content) {
        QStringList words = line.split(' ');
        QString currentLine;
        int currentLineWidth = 0;

        foreach (const QString& line, m_msg.content) {
            int xPos = m_isSelf ? m_contentRect.right() - 5 : m_contentRect.left();
            int currentLineWidth = 0;
            QString currentLine;

            // 改为逐个字符处理
            for (int i = 0; i < line.length(); ++i) {
                QChar ch = line[i];
                int charWidth = fm.horizontalAdvance(ch);

                // 强制换行条件：当前行宽+字符宽超过可用宽度
                if (currentLineWidth + charWidth > availableWidth) {
                    drawAlignedLine(painter, currentLine, y, availableWidth);
                    y += lineHeight;
                    currentLine.clear();
                    currentLineWidth = 0;
                    xPos = m_isSelf ? m_contentRect.right() - 5 : m_contentRect.left();
                }

                currentLine.append(ch);
                currentLineWidth += charWidth;
            }

            // 绘制剩余内容
            if (!currentLine.isEmpty()) {
                drawAlignedLine(painter, currentLine, y, availableWidth);
                y += lineHeight;
            }
        }

        if (!currentLine.isEmpty()) {
            drawAlignedLine(painter, currentLine, y, availableWidth);
            y += lineHeight;
        }
    }
    painter.restore();
}
void QQMessageWidget::drawAlignedLine(QPainter& painter, const QString& text, int y, int maxWidth) {
    int textWidth = painter.fontMetrics().horizontalAdvance(text);
    int x = m_isSelf ?
                (m_contentRect.right() - textWidth - 5) :  // 右侧留5px边距
                m_contentRect.left();

    // 边界保护
    x = qBound(m_contentRect.left(), x, m_contentRect.right() - textWidth);

    painter.drawText(x, y + painter.fontMetrics().ascent(), text);  // 使用ascent保证垂直居中
}
void QQMessageWidget::paintTimestamp(QPainter& painter) {
    painter.save();
    painter.setFont(QFont("Arial", 8));
    painter.setPen(QColor(150, 150, 150));

    QDateTime dt = QDateTime::fromString(m_msg.timestamp, "MM-dd hh:mm:ss");
    QString timeText = dt.toString("hh:mm");

    painter.drawText(m_timeRect, Qt::AlignRight | Qt::AlignVCenter, timeText);
    painter.restore();
}
void QQMessageWidget::paintAvatar(QPainter& painter) {
    painter.save();
    QPainterPath path;
    path.addEllipse(m_avatarRect);
    painter.setClipPath(path);

    // 示例头像绘制，实际应替换为真实头像
    painter.fillRect(m_avatarRect, QColor(200, 200, 200));
    painter.setPen(Qt::darkGray);
    painter.drawEllipse(m_avatarRect);

    painter.restore();
}
